package com.misty.blog.controller.blogController;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.misty.blog.service.BlogService;
import com.misty.blog.service.UsersService;
import com.misty.common.bean.Result;
import com.misty.dao.domain.Blog;
import com.misty.dao.domain.ConcernList;
import com.misty.dao.domain.Users;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/fore/user")
public class UsersController {


    @Autowired
    private UsersService usersService;

    @Autowired
    private BlogService blogService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;


    @GetMapping("/{id}")
    public Result<?> personWithBlog(@PathVariable(name = "id") Integer userId){
        //根据ID查询用户
        Users user = usersService.selectByUserId(userId);
        if(ObjectUtil.isEmpty(user)){
            return Result.error("没有此用户");
        }
//        存储返回前端信息
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("user",user);

        //根据该用户查询所有博客
        List<Blog> blog = blogService.selectAllByUserId(userId);
        if(CollUtil.isEmpty(blog)){
//            return Result.error("该用户无博客！");
            hashMap.put("blog",null);
        }else {
            hashMap.put("blog",blog);
        }

        return Result.success("查询用户和博客成功!",hashMap);
    }
    @GetMapping("/load/{id}")
    public Result<?> personInfo(@PathVariable(name = "id") Integer userId){

        //根据该用户查询所有博客
        Users users = usersService.selectByUserId(userId);
        if(users == null){
            return Result.error("没有此用户");
        }

        return Result.success("查询用户成功!",users);
    }


    @PutMapping("/modifyPersonalData")
    @ApiOperation(value = "修改个人信息")
    @PreAuthorize("hasAuthority('fore/user')")
    public Result<?> modifyPersonalData(@RequestBody Users user){
        user.setUpdateTime(LocalDateTime.now());
        boolean update = usersService.updateById(user);
        if(!update){
            return Result.error();
        }
        return Result.success("修改个人信息成功!");
    }


    @PostMapping("/concern")
    @ApiOperation(value = "关注")
    @PreAuthorize("hasAuthority('fore/user')")
    public Result<?> concern(@RequestBody ConcernList concernList){
        return usersService.concern(concernList);
    }

    @GetMapping("/getConcernList")
    @ApiOperation(value = "获取关注列表")
    @PreAuthorize("hasAuthority('fore/user')")
    public Result<?> getConcernList(ConcernList concernList){
        return usersService.getConcernList(concernList);
    }

}
